package com.hpin.fansea.my;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.base.BaseActivity;
import com.hpin.fansea.bean.LoadPicResult;
import com.hpin.fansea.bean.ModifyInfo;
import com.hpin.fansea.bean.ResultBaseBean;
import com.hpin.fansea.bean.UpdateInfo;
import com.hpin.fansea.ui.HomeActivity;
import com.hpin.fansea.utils.CommonUtils;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.utils.LogUtil;
import com.hpin.fansea.widget.ActionSheetDialog;
import com.hpin.fansea.widget.CircleImageView;
import com.lidroid.xutils.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;

import java.io.File;
import java.util.Calendar;

/**
 * 我的信息修改页面
 * Created by Aaron on 15/9/19.
 */
public class ModifyInfoActivity extends BaseActivity {

    private DisplayImageOptions options;
    private EditText et_psw;
    private EditText et_psw2;
    private EditText et_email;
    private EditText et_username;
    private TextView tv_community_show;
    private TextView tv_candler;

    private String headImgUrl;  //保存上传的头像的地址

    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 1061;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 1062;
    /** 裁剪 */
    private static final int PHOTO_RESOULT = 1063;

    private final String IMAGE_UNSPECIFIED = "image/*";

    /*拍照的文件保存的位置*/
    private File currentFile;
    private CircleImageView head_img;
    private RadioButton rb_male_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_modify_my_info);

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.icon_headpic_default)
                .showImageForEmptyUri(R.mipmap.icon_headpic_default)
                .showImageOnFail(R.mipmap.icon_headpic_default)
                .resetViewBeforeLoading(true)
                .cacheOnDisk(true).cacheInMemory(true)
                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .considerExifParams(true)
                .displayer(new SimpleBitmapDisplayer()).build();

        initWidget();

    }

    private void initWidget() {

        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.my_info));

        iv_left.setOnClickListener(this);

        setHeadInfo();

        TextView tv_phone = (TextView) findViewById(R.id.tv_phone);
        et_psw = (EditText) findViewById(R.id.et_psw);
        et_psw2 = (EditText) findViewById(R.id.et_psw2);

        et_email = (EditText) findViewById(R.id.et_email);
        et_username = (EditText) findViewById(R.id.et_username);

        rb_male_button = (RadioButton) findViewById(R.id.radioMale);
        RadioButton rb_female_button = (RadioButton) findViewById(R.id.radioFemale);

        tv_community_show = (TextView) findViewById(R.id.tv_community_show);
        tv_candler = (TextView) findViewById(R.id.tv_candler);

        Button btn_commit = (Button) findViewById(R.id.btn_commit);

        //性别
        if (Constant.SEX_FREMALE.equals(sp.getString(Constant.gender, ""))) {

            rb_female_button.setSelected(true);
            rb_male_button.setSelected(false);

        } else {

            rb_female_button.setSelected(false);
            rb_male_button.setSelected(true);

        }

        tv_phone.setText(sp.getString(Constant.mobile, ""));
        et_email.setText(sp.getString(Constant.email, ""));
        et_psw.setText(sp.getString(Constant.password, ""));
        et_psw2.setText(sp.getString(Constant.password, ""));
        et_username.setText(sp.getString(Constant.nickname, ""));
        tv_community_show.setText(sp.getString(Constant.communityName, ""));
        tv_candler.setText(sp.getString(Constant.birthday, ""));

        btn_commit.setOnClickListener(this);
        tv_candler.setOnClickListener(this);

    }

    private void setHeadInfo() {

        // 头像
        head_img = (CircleImageView) findViewById(R.id.head_img);

        ImageLoader.getInstance().displayImage(sp.getString(Constant.headPic, ""), head_img, options);

        // 认证的图片
        ImageView my_auth = (ImageView) findViewById(R.id.my_auth);
        TextView tv_username = (TextView) findViewById(R.id.tv_username);
        TextView tv_community = (TextView) findViewById(R.id.tv_community);

        if (Constant.AUTH_USER.equals(sp.getString(Constant.status, "")) || Constant.AUTH_PASSED.equals(sp.getString(Constant.status, "")))
            my_auth.setVisibility(View.VISIBLE);
        else
            my_auth.setVisibility(View.INVISIBLE);

        tv_username.setText(sp.getString(Constant.nickname, ""));
        tv_community.setText(sp.getString(Constant.communityName, ""));

        head_img.setOnClickListener(this);

    }

    /**
     * 弹出选择照片的对话框
     */
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }

    /**
     * 相册
     */
    private void getFromPhotoAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
        startActivityForResult(intent, PHOTO_ALBUM_CODE);
    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + Constant.PHOTO_CACHE;
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, "temp.jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case PHOTO_ALBUM_CODE://从相册中选择

                if (data == null)
                    return;

                startPhotoZoom(data.getData());

                break;

            case TAKE_PHOTO_CODE://拍照
                // 获取文件保存路径
                File picture = new File(Environment.getExternalStorageDirectory().getPath() + Constant.PHOTO_CACHE
                        + "/temp.jpg");

                LogUtil.e("tag", "文件保存路径===>>" + picture.getAbsolutePath());

                startPhotoZoom(Uri.fromFile(picture));

                break;

            case PHOTO_RESOULT://裁剪

                // 把图片显示在 头像的位置上
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");

                    //上传头像
                   loadImg(photo);

                }

            break;

        }

    }

    /**
     * 上传头像
     * @param photo
     */
    private void loadImg(final Bitmap photo) {

        new Thread(

                new Runnable() {
                    @Override
                    public void run() {
                        String upResult = HttpUtil.getInstance().load(Constant.WEB_ROOT + Constant.UPLOADPIC + "/" + sp.getString(Constant.token, ""), CommonUtils.compressByte(photo));

                        try {
                            LogUtil.e("tag", "上传头像后返回的数据==>" + upResult);

                            final LoadPicResult loadPicResult = JSONObject.parseObject(upResult, LoadPicResult.class);

                            if (Constant.STATUS_SUCESS.equals(loadPicResult.status)) {

                                //上传成功,保存到上传的集合中
                                headImgUrl = loadPicResult.result;

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //显示图片到控件上
                                        ImageLoader.getInstance().displayImage(loadPicResult.result, head_img);
                                    }
                                });

                            }else {
                                showToast("头像上传失败");
                            }

                        } catch (Exception e) {
                            showToast("头像上传失败");
                            e.printStackTrace();
                        }

                    }
                }

        ).start();

    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:

                finish();

                break;

            case R.id.btn_commit:// 完成

                String pwd = et_psw.getText().toString().trim();
                String pwd2 = et_psw2.getText().toString().trim();

                if (sp.getString(Constant.password, "").equals(et_psw.getText().toString().trim())) {
                    //第一个 未修改过密码
                    if (!pwd.equals(pwd2)) {
                        showToast("两次密码不一样！");
                        return;
                    }

                } else if (et_psw.getText().toString().trim().length() < 6 || et_psw.getText().toString().trim().length() > 16) {
                    showToast("密码须在6-16位之间!");
                    return;

                }

                if (!pwd.equals(pwd2)) {
                    showToast("两次密码不一样！");
                    return;
                }

                if (CommonUtils.isNull(et_username.getText().toString().trim())) {
                    showToast("请输入昵称");
                }

                //修改
                commitModifyData();

                break;

            case R.id.head_img:
                //更换头像

                showChoose();

                break;
            case R.id.tv_candler:
                //更改生日日期

                Calendar c = Calendar.getInstance();

                new DatePickerDialog(ModifyInfoActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {

                        String month = (monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1) : (monthOfYear + 1) + "";
                        String day = dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth + "";
//                        String currDay = year + "/" + month + "/" + day;

                        tv_candler.setText(year + "-" + month + "-" + day);

                    }

                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
                        c.get(Calendar.DAY_OF_MONTH)).show();

                break;

        }

    }

    /**
     * 提交修改数据
     */
    private void commitModifyData() {
        
        ModifyInfo userInfo = new ModifyInfo();

        userInfo.birthDay = CommonUtils.isNull(tv_candler.getText().toString().trim()) ? "" : tv_candler.getText().toString().trim();
        userInfo.email = et_email.getText().toString().trim();
        userInfo.gender = rb_male_button.isChecked()? Constant.SEX_MALE : Constant.SEX_FREMALE;
        userInfo.nickname = et_username.getText().toString().trim();
        userInfo.photo = CommonUtils.isNull(headImgUrl) ? sp.getString(Constant.headPic, "") : headImgUrl;
        userInfo.userId = sp.getString(Constant.userId, "");
        userInfo.userPwd =
                sp.getString(Constant.password,"").equals(et_psw.getText().toString().trim()) ?
                        sp.getString(Constant.password,"") : CommonUtils.toMd5(et_psw.getText().toString().trim().getBytes()) ;

        UpdateInfo uInfo = new UpdateInfo();
        uInfo.systemType = Constant.SYSTEM_TYPE;
        uInfo.token= sp.getString(Constant.token, "");

        JSONObject outObj = (JSONObject) JSONObject.toJSON(uInfo);
        JSONObject fixObj = (JSONObject) JSONObject.toJSON(userInfo);

        outObj.put("userInfo", fixObj);

        String jsonSend = JSONObject.toJSONString(outObj);

        RequestParams params = new RequestParams();

        params.addBodyParameter("modifyUser", jsonSend);

        HttpUtil.getInstance().setPostRequest("提交中...", this, Constant.WEB_ROOT + Constant.FIXMYINFO, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    ResultBaseBean resultBaseBean = JSONObject.parseObject(str, ResultBaseBean.class);

                    if (Constant.STATUS_SUCESS.equals(resultBaseBean.status)) {

                        showToast("修改成功");

                        SharedPreferences.Editor edit = sp.edit();

                        edit.putString(Constant.email, et_email.getText().toString().trim());
                        edit.putString(Constant.password, sp.getString(Constant.password,"").equals(et_psw.getText().toString().trim()) ?
                                sp.getString(Constant.password,"") : CommonUtils.toMd5(et_psw.getText().toString().trim().getBytes()));
                        edit.putString(Constant.nickname, et_username.getText().toString().trim());
                        edit.putString(Constant.gender, rb_male_button.isChecked() ? Constant.SEX_MALE : Constant.SEX_FREMALE);
                        edit.commit();

                        Intent mIntent = new Intent(ModifyInfoActivity.this, HomeActivity.class);
                        startActivity(mIntent);

                    }else  {
                        showToast(resultBaseBean.message);
                    }

                }catch (Exception e) {
                    e.printStackTrace();
                    showToast("信息修改失败");
                }

            }
        }, null);

    }
}